package dxunderground.winampController.Server.GUI;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import dxunderground.winampController.Common.GUI;
import dxunderground.winampController.Server.Server;

@SuppressWarnings("serial")
public class ServerPanel extends JPanel {
	private JList list;
	private DefaultListModel listModel;
	private Thread serverThread;
	private Server server;

	public ServerPanel(ButtonActions buttonActions, GUI gui) {
		JLabel serverLabel = new JLabel("Connections:");

		listModel = new DefaultListModel();
		list = new JList(listModel);
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		list.setLayoutOrientation(JList.VERTICAL);

		JScrollPane listScroller = new JScrollPane(list);

		this.setLayout(new BorderLayout());
		this.add(serverLabel, BorderLayout.NORTH);
		this.add(listScroller, BorderLayout.CENTER);

		this.setPreferredSize(new Dimension(75, 0));

		server = new Server(buttonActions, gui, listModel);
		serverThread = new Thread(server);
		serverThread.start();
	}

	public void stopServer() {
		server.setListening(false);
		String host = "localhost";
		try {
			Socket socket = new Socket(host, 4444);
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			out.println("__END__");
		} catch (UnknownHostException e) {
			System.err.println("Don't know about host: " + host);
		} catch (IOException e) {
			System.err.println("Couldn't get I/O for the connection to: " + host);
		}
	}
}
